package wiz.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ChruszczRemoteWizIntegration implements WizIntegration {

	private WizServiceAsync fWizService;


	public ChruszczRemoteWizIntegration(WizServiceAsync wizService) {
		fWizService = wizService;
	}

	@Override
	public boolean canPullPlayerListFromRemoteSystem() {
		return true;
	}

	@Override
	public void pullPlayerNames(final AsyncCallback<List<String>> callback) {
		fWizService.getPlayerNames(new AsyncCallback<String>() {
			@Override
			public void onSuccess(String result) {
				
				parseChruszczPageResult(callback, result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				callback.onFailure(caught);
			}
		});
	}

	@Override
	public boolean canSubmitScoresToRemoteSystem() {
		return false;
	}

	@Override
	public void submitScores(List<GameResult> result) {
		//TODO: automated form submit. Should be easy?
	}

	private void parseChruszczPageResult(final AsyncCallback<List<String>> callback, String result) {
		List<String> names = new ArrayList<String>();
		
		DivElement createDivElement = Document.get().createDivElement();
		createDivElement.setInnerHTML(result);
		
		NodeList<Element> elementsByTagName = createDivElement.getElementsByTagName("select"); //$NON-NLS-1$
		for (int i = 0; i < elementsByTagName.getLength(); i++) {
			Element item = elementsByTagName.getItem(i);
			if ("id_form-0-player".equals(item.getId())) { //$NON-NLS-1$
				NodeList<Element> elementsByTagName2 = item.getElementsByTagName("option"); //$NON-NLS-1$
				for (int j = 0; j < elementsByTagName2.getLength(); j++) {
					Element nameNode = elementsByTagName2.getItem(j);
					if (!nameNode.getInnerText().startsWith("-")) { //$NON-NLS-1$

						names.add(nameNode.getInnerText());
					}
				}
				break;
			}
		}
		callback.onSuccess(names);
	}

}
